﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Data;
using nRoute.Components;
using System.Windows.Interactivity;
#if WP7
using nRoute.Behaviors.Interactivity;
#endif

namespace nRoute.Behaviors
{
    public class BridgeCommandBehavior
#if WP7
        : BindableBehavior<FrameworkElement>
#else
        : Behavior<DependencyObject>
#endif
    {
        public static readonly DependencyProperty CommandRelayProperty =
            DependencyProperty.Register("CommandRelay", typeof(CommandRelay), typeof(BridgeCommandBehavior),
                new PropertyMetadata(null, OnCommandRelayChanged));

        public static readonly DependencyProperty CommandSourceProperty =
            DependencyProperty.Register("CommandSource", typeof(ICommand), typeof(BridgeCommandBehavior),
                new PropertyMetadata(null, OnCommandSourceChanged));

#region Properties

        [Category("Common Properties")]
        public CommandRelay CommandRelay 
        {
            get { return (CommandRelay)GetValue(CommandRelayProperty); }
            set { SetValue(CommandRelayProperty, value); }
        }

        [Category("Common Properties")]
#if (!WP7)
        [CustomPropertyValueEditor(CustomPropertyValueEditor.PropertyBinding)]
#endif
        public ICommand CommandSource
        {
            get { return (ICommand)GetValue(CommandSourceProperty); }
            set { SetValue(CommandSourceProperty, value); }
        }

#if WP7

        [Category("Common Properties")]
#if (!WP7)
        [CustomPropertyValueEditor(CustomPropertyValueEditor.PropertyBinding)]
#endif
        public Binding CommandSourceBinding
        {
            get { return GetBinding(CommandSourceProperty); }
            set { SetBinding<ICommand>(CommandSourceProperty, value); }
        }

#endif

#endregion

#region Handlers

        private static void OnCommandSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((BridgeCommandBehavior)d).UpdateRelay();
        }

        private static void OnCommandRelayChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((BridgeCommandBehavior)d).UpdateRelay();
        }

#endregion

#region Overrides

        protected override void OnAttached()
        {
            base.OnAttached();
#if WP7
            base.ApplyAllPendingBindings();
#endif
            UpdateRelay();
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
#if WP7
            base.ClearAllBindings();
#endif
        }

#endregion

#region Helpers
        
        private void UpdateRelay()
        {
            if (CommandRelay != null && this.CommandSource != null)
            {
                CommandRelay.Command = CommandSource;
            }
        }

#endregion

    }
}
